package com.haois.component.security;

import com.haois.component.common.enu.JwtEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;


/**
 * description
 *
 * @author RuiHaoZ on GCU
 * @date 2017/3/17 9:18
 */
public class HandleCookie {

    private static Logger logger = LoggerFactory.getLogger(HandleCookie.class);


    public static HttpServletResponse saveCookie(HttpServletResponse response,
                                                 String cookieName, String cookieValue) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        try {
            URLEncoder.encode(cookieValue, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.addCookie(cookie);
        // logger.info("保存cookie到本地,name =[{}]",cookieName);
        return response;
    }

    public static HttpServletResponse deleteCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return response;
    }

    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        Cookie cookie = null;
        for (Cookie cookie_ : cookies) {
            if (cookie_.getName().equals(name)) {
                cookie = cookie_;
            }
        }
        return cookie;
    }

    public static String getValueByName(HttpServletRequest request, String name) {
        String token = "";
        String from = request.getHeader("fromWhere");
        if (JwtEnum.CHAT.getCookieName().equals(name) && "weChat".equals(from)) {
            token = request.getHeader("JSONWebTokens");
        } else {
            Cookie cookie = getCookieByName(request, name);
            if (cookie == null) {
                throw new NullPointerException("Cookie不存在");
            }
            token = cookie.getValue();
        }
        return token;
    }


    public static HttpServletResponse updateCookie(String subject, HttpServletResponse response, Date IssuedTime, String cookieName) {
        ProduceJwt produceJwt = new ProduceJwt();
        String jwt = produceJwt.produceToken(subject,IssuedTime, JwtEnum.WEB);
        // logger.info("更新cookie到本地,name =[{}],value=[{}]");
        return HandleCookie.saveCookie(response, cookieName, jwt);
    }

}


